package cn.samir.sudoku.core;

import java.util.ArrayList;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import cn.samir.sudoku.db.dao.SudokuDao;
import cn.samir.sudoku.util.LogUtils;
import cn.samir.sudoku.util.Utils;

public class Number99View extends ViewGroup implements ItemClickListener,
		ItemValueChangedListener {

	private static final String TAG = "BackgroundView";
	// ArrayList<SudokuSubItem> items;
	ArrayList<SubItemView> views;
	Sudokus game;
	int screenWidth;
	int screenHeight;
	int mSquareNum = 9;
	int mNumbers; // 99 81
	int paddings = 20;
	int clickPosX;
	int clickPosY;
	InputNumberListener inputNumberListener;
	SubItemView mFocusedView;
	/**
	 * 是否需要提示，如果不需要，则默认显示所填的值是正确的
	 */
	boolean isNeedHelp = true;

	public Number99View(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		inits();
	}

	private void inits() {
		// TODO Auto-generated method stub
		// items = new ArrayList<SudokuSubItem>();
		views = new ArrayList<SubItemView>();
		mNumbers = mSquareNum * mSquareNum;
		for (int i = 0; i < mSquareNum; i++) {
			for (int j = 0; j < mSquareNum; j++) {
				int x = j;
				int y = i;
				SudokuSubItem sudokuSubItem = new SudokuSubItem(x, y);
				sudokuSubItem.value = 0;
				SubItemView itemView = new SubItemView(getContext());
				itemView.setItemClickListener(this);
				// setBorderFlag(x,y,itemView);
				itemView.setSudokuSubItem(sudokuSubItem);
				// itemView.setValue(i+1);
				views.add(i * mSquareNum + j, itemView);
				addView(itemView, i * mSquareNum + j);
			}
		}

		// this.game = DefaultGames.getOne();
		// initGames();
		// setGame(null);
	}

	public int getPosition(int i, int j) {
		return (i * mSquareNum + j);
	}

	public int getmSquareNum() {
		return mSquareNum;
	}

	public void setmSquareNum(int mSquareNum) {
		this.mSquareNum = mSquareNum;
		mNumbers = mSquareNum * mSquareNum;
	}

	public Sudokus getGame() {
		return game;
	}

	public void setGame(Sudokus game) {
		this.game = game;
		initGames();
		// invalidate();
	}

	public InputNumberListener getInputNumberListener() {
		return inputNumberListener;
	}

	public void setInputNumberListener(InputNumberListener inputNumberListener) {
		this.inputNumberListener = inputNumberListener;
	}

	private void initGames() {
		String content = game.content;
		if (!TextUtils.isEmpty(content) && content.length() == mNumbers) {
			for (int i = 0; i < mSquareNum; i++) {
				for (int j = 0; j < mSquareNum; j++) {
					int id = i * mSquareNum + j;
					SubItemView itemView = (SubItemView) getChildAt(id);
					itemView.setPreDefValue(content.charAt(id) - '0');
					Log.i(TAG, "id=" + (id));
				}
			}
		}
	}

	public Number99View(Context context, AttributeSet attrs) {
		super(context, attrs);
		inits();

	}

	public Number99View(Context context) {
		super(context);
		inits();

	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {

		// int mesureHeight = getMeasuredHeight();
		int mesureWidth = getMeasuredWidth() - paddings;
		int splitWidth = mesureWidth / mSquareNum;
		// for (int i = 0; i < mNumbers; i++) {//先横向布局，到9个后纵向布局
		//
		// View child = getChildAt(i);
		// child.layout((i%mSquareNum)*splitWidth, (i/mSquareNum)*splitWidth,
		// (i%mSquareNum+1)*splitWidth, (i/mSquareNum)*splitWidth);
		// }

		/*
		 * left，right代表的是x轴的值，top，buttom是y轴的值
		 */
		for (int i = 0; i < mSquareNum; i++) {
			for (int j = 0; j < mSquareNum; j++) {
				View child = getChildAt(i * mSquareNum + j);
				int left = j * splitWidth + paddings / 2;// 横向的是y不变,x变化，因此x的值是j，y的值是i
				int top = i * splitWidth;
				int right = left + splitWidth;
				int buttom = top + splitWidth;
				child.layout(left, top, right, buttom);
			}
		}

	}

	@Override
	public void onItemClick(SubItemView sudokuSubItem) {
		mFocusedView = sudokuSubItem;
		performItemClick(sudokuSubItem);
		if (inputNumberListener != null) {
			inputNumberListener.readyInput(sudokuSubItem);
		}
		Log.i(VIEW_LOG_TAG, "backView_onItemClick");
	}

	public SubItemView getFocusedView() {
		return mFocusedView;
	}

	private void performItemClick(SubItemView sudokuSubItem) {
		int x = sudokuSubItem.getSudokuSubItem().xPoint;
		int y = sudokuSubItem.getSudokuSubItem().yPoint;
		int groupNumber = sudokuSubItem.getSudokuSubItem().groupNum;
		// GlobalStatus.setSudokuSubItem(sudokuSubItem);
		for (int i = 0; i < mSquareNum; i++) {
			for (int j = 0; j < mSquareNum; j++) {
				SubItemView subItemView = (SubItemView) views.get(i
						* mSquareNum + j);
				int sx = subItemView.getSudokuSubItem().xPoint;
				int sy = subItemView.getSudokuSubItem().yPoint;
				int sgroupNum = subItemView.getSudokuSubItem().groupNum;
				if (subItemView == sudokuSubItem) {
					subItemView
							.setBackgroundColor2(SubItemView.SELECTED_ONE_COLOR);
				} else if (x == sx || y == sy || groupNumber == sgroupNum) {
					subItemView.setBackgroundColor2(SubItemView.SELECTED_COLOR);
				} else {
					subItemView.setBackgroundColor2(SubItemView.DEFAULT_COLOR);
				}
			}
		}

	}

	public void handleAction(MoveAction moveAction) {
		switch (moveAction.action) {
		case MoveAction.INPUT_CLEAR:
			if (mFocusedView != null) {
				mFocusedView.clear();
			}
			break;
		case MoveAction.INPUT_HELP:
			break;

		case MoveAction.INPUT_MARK:
			if (mFocusedView != null) {
				mFocusedView.addMark(moveAction.value);
			}
			break;

		case MoveAction.INPUT_NUMBER:
			if (mFocusedView != null) {
				mFocusedView.setValue(moveAction.value);
				onItemChanged(mFocusedView, moveAction.value);
				if (checkAllValues()) {
					onCompelete();
				}
			}
			break;

		case MoveAction.INPUT_PRE_STEP:
			break;

		case MoveAction.INPUT_REBACK:
			break;
		}
	}

	private boolean checkAllValues() {
		for (int i = 0; i < mSquareNum; i++) {
			for (int j = 0; j < mSquareNum; j++) {
				SubItemView subItemView = views.get(getPosition(i, j));
				if (subItemView.mFlagValueOk == SubItemView.VALUE_OK) {
					continue;
				} else {
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		LogUtils.i(VIEW_LOG_TAG, "b_onKeyDown");
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {

		case MotionEvent.ACTION_OUTSIDE:
			LogUtils.i(VIEW_LOG_TAG, "ACTION_OUTSIDE");
			break;

		default:
			LogUtils.i(VIEW_LOG_TAG, "onInterceptTouchEvent");
			break;
		}
		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public void onItemChanged(SubItemView subItemView, int value) {
		if (subItemView == null || !Utils.isNumberLegal(value)) {
			return;
		}
		if (Utils.getConfig(getContext(), "isHelpButtonEnabled") == Utils.ENABLE) {
			// 设置开关
			setValue(subItemView, value, SubItemView.VALUE_OK,
					SubItemView.VALUE_OK);
			return;
		}
		// boolean isValueOk = true;
		SudokuSubItem item = subItemView.mSudokuSubItem;
		for (int i = 0; i < mSquareNum; i++) {
			for (int j = 0; j < mSquareNum; j++) {
				SubItemView subitemView = views.get(getPosition(i, j));
				LogUtils.i(TAG,
						"subitemView=" + subitemView.mSudokuSubItem.toString());
				if (subitemView != null) {
					// 与自己相比
					if (subItemView.mSudokuSubItem.xPoint == subitemView.mSudokuSubItem.xPoint
							&& subItemView.mSudokuSubItem.yPoint == subitemView.mSudokuSubItem.yPoint) {
						LogUtils.i(TAG, "ziji,"
								+ subitemView.mSudokuSubItem.xPoint + ","
								+ subitemView.mSudokuSubItem.yPoint);
						continue;
					}
					// 横向方向有相同值，不可以
					else if ((subitemView.mSudokuSubItem.xPoint == item.xPoint)
							&& (subitemView.mSudokuSubItem.value == item.value)) {
						setValue(subItemView, value, SubItemView.VALUE_ERROR,
								SubItemView.VALUE_ERROR);
						LogUtils.i(TAG, "横向方向有相同值，不可以,"
								+ subitemView.mSudokuSubItem.toString() + ","
								+ item.toString());
						return;
					} else if ((subitemView.mSudokuSubItem.yPoint == item.yPoint)
							&& (subitemView.mSudokuSubItem.value == item.value)) {
						setValue(subItemView, value, SubItemView.VALUE_ERROR,
								SubItemView.VALUE_ERROR);
						LogUtils.i(TAG, " 纵向方向有相同值，不可以,"
								+ subitemView.mSudokuSubItem.toString() + ","
								+ item.toString());
						return;
					} else if ((subitemView.mSudokuSubItem.groupNum == item.groupNum)
							&& (subitemView.mSudokuSubItem.value == item.value)) {
						setValue(subItemView, value, SubItemView.VALUE_ERROR,
								SubItemView.VALUE_ERROR);
						LogUtils.i(TAG, "同一组有相同值，不可以,"
								+ subitemView.mSudokuSubItem.toString() + ","
								+ item.toString());
						return;
					}
				}
			}
		}
		// subItemView.setValue(value, SubItemView.VALUE_OK,
		// SubItemView.VALUE_OK);
		setValue(subItemView, value, SubItemView.VALUE_OK, SubItemView.VALUE_OK);
	}

	private void setValue(SubItemView subItemView, int value, int isok, int real) {
		if (isNeedHelp) {
			subItemView.setValue(value, isok, real);
		} else {
			subItemView.setValue(value, SubItemView.VALUE_OK, real);
		}
	}

	public boolean isNeedHelp() {
		return isNeedHelp;
	}

	public void setNeedHelp(boolean isNeedHelp) {
		this.isNeedHelp = isNeedHelp;
	}

	@Override
	public void onCompelete() {

		SudokuDao dao = new SudokuDao(getContext());
		game.passed = 1;
		game.fullContent = toString();
		game.code = Utils.getSharePreString(getContext(), "code")+"";
		dao.update(game);
		if (inputNumberListener != null) {
			inputNumberListener.onFullCompeleteSuccess(game);
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(game.content);
		for (int i = 0; i < mSquareNum; i++) {
			for (int j = 0; j < mSquareNum; j++) {
				SubItemView itemView = views.get(getPosition(i, j));
				sb.setCharAt(getPosition(i, j),
						(char) (itemView.getmValue() + '0'));
			}
		}
		return sb.toString();
	}

}
